package com.yzt.zhuju.base;

import android.annotation.TargetApi;
import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.LinearLayout;

import com.yzt.zhuju.R;
import com.yzt.zhuju.event.RxBus;
import com.yzt.zhuju.event.web.WebViewEvent;
import com.yzt.zhuju.network.HttpUrlManager;
import com.yzt.zhuju.utils.ViewUtils;
import com.yzt.zhuju.webview.AppWebChromeClient;
import com.yzt.zhuju.webview.AppWebViewClient;
import com.yzt.zhuju.webview.BaseWebView;
import com.yzt.p_base.utils.ToastUtil;

import java.util.Map;

/**
 * author : bob
 * date   : 2022/12/9
 * desc   :
 */
public abstract class BaseWebViewActivity extends BaseActivity {

    private String mUrl;
    protected WebView mWebView;
    private BaseWebView mBaseWebView;
    private ValueCallback<Uri[]> mUploadCallbackAboveL;
    private ValueCallback<Uri> mUploadMessage;
    public LinearLayout llBackContainer;

    private View backViewLine;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //视频为了避免闪屏和透明问题
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_base_webview;
    }

    @Override
    protected void onResume() {
        super.onResume();
        RxBus.getDefault().post(new WebViewEvent());
    }

    @Override
    public void installViews() {
        setFullScreen(true, R.color.white);
        mUrl = getUrl();
        String mHeadGSon = getHeadGson();
        mBaseWebView = findViewById(R.id.activity_webview_layout);
        mWebView = mBaseWebView.getWebView();
        llBackContainer = findViewById(R.id.ll_back_container);
        mWebView.setWebChromeClient(new AppWebChromeClient(this, new AppWebChromeClient.OnWebChromeListener() {
            @Override
            public void onOpenFileChooser(ValueCallback<Uri> uploadMsg) {
                mUploadMessage = uploadMsg;
            }

            @Override
            public void onShowFileChooser(ValueCallback<Uri[]> filePathCallback) {
                mUploadCallbackAboveL = filePathCallback;
            }
        }));
        mAppWebViewClient.setActivity(mActivity);
        mWebView.setWebViewClient(mAppWebViewClient);
        WebView.setWebContentsDebuggingEnabled(true);
        WebSettings settings = mWebView.getSettings();
        settings.setAllowFileAccessFromFileURLs(true);
        settings.setAllowUniversalAccessFromFileURLs(true);
        settings.setAllowFileAccess(true);
        mBaseWebView.loadUrl(mUrl, mHeadGSon);

        llBackContainer.setVisibility(View.GONE);
        llBackContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        backViewLine = findViewById(R.id.back_view_line);
        backViewLine.getLayoutParams().height = ViewUtils.getStatusBarHeight(this) / 2;
    }

    private final AppWebViewClient mAppWebViewClient = new AppWebViewClient(this, new AppWebViewClient.WebViewListener() {

        @Override
        public void finish() {
            BaseWebViewActivity.this.finish();
        }

        @Override
        public void turnOtherPage(String turnType, Map<String, String> params) {
            turnToOtherPage(turnType, params);
        }

        @Override
        public void turnByARouter(String url) {
            turnToByARoute(url);
        }

        @Override
        public void turnOpenBrowser(String url) {
            try {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                startActivity(intent);
            } catch (ActivityNotFoundException e) {
                ToastUtil.showMessage(R.string.not_found_browser);
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            BaseWebViewActivity.this.onPageFinished(view, url);
            closeProgress();
        }
    });

    /**
     * 资源加载完成
     */
    public void onPageFinished(WebView view, String url) {

    }

    /**
     * 根据类型跳转
     */
    public abstract void turnToOtherPage(String turnType, Map<String, String> params);

    /**
     * 根据路由跳转
     */
    public abstract void turnToByARoute(String url);

    public abstract String getUrl();

    public abstract String getHeadGson();

    public abstract boolean getCleanCookie();

    public abstract int getStatusBarHeight();

    /**
     * 更新判断是否是全面屏 倾入式状态栏
     */
    public void updateStatusBarHeight() {
        try {
            if (mWebView != null) {
                String hostStr = HttpUrlManager.getAppHttpUrl();

                // 历史方式 - 比对域名是否全屏
                boolean withMatch = mUrl.startsWith(hostStr);

                // new - 捕获地址中的参数值，判断全屏 key = fullScreen
                String keyCode = getValueByName(mUrl, "fullScreen");

                // value = full
                if (keyCode != null && !"".equals(keyCode)) {
                    withMatch = "full".equals(keyCode);
                }

                // 设置全屏
                setFullScreen(withMatch);
            }
        } catch (Exception ignored) {

        }
    }

    /**
     * 抓取指定key的value
     *
     * @param url  地址
     * @param name 关键字
     */
    private String getValueByName(String url, String name) {
        String result = "";
        if (url == null || "".equals(url)) {
            return result;
        }
        int index = url.indexOf("?");
        String temp = url.substring(index + 1);
        String[] keyValue = temp.split("&");
        for (String str : keyValue) {
            if (str.contains(name)) {
                result = str.replace(name + "=", "");
                break;
            }
        }
        return result;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mWebView != null && mWebView.canGoBack()) {
                mWebView.goBack();
                updateStatusBarHeight();
                return true;
            } else {
                closeProgress();
                this.finish();
//                if (mHeader != null && mHeader.containsKey("Referer")) {
////                    BaseBus.sendMessage(new BaseBus.BusEvent(BaseBus.PayWeiXinH5Result));
//                }
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            if (requestCode == AppWebChromeClient.FILE_CHOOSER_RESULT_CODE || requestCode == AppWebChromeClient.RECORD_VIDEO) {
                if (null == mUploadMessage && null == mUploadCallbackAboveL) {
                    return;
                }
                Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
                if (mUploadCallbackAboveL != null) {
                    onActivityResultAboveL(requestCode, resultCode, data);
                } else if (mUploadMessage != null) {
                    mUploadMessage.onReceiveValue(result);
                    mUploadMessage = null;
                }
            }
        } catch (Exception ignored) {

        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
        if ((requestCode == AppWebChromeClient.FILE_CHOOSER_RESULT_CODE
                || requestCode == AppWebChromeClient.RECORD_VIDEO)
                && mUploadCallbackAboveL != null) {
            Uri[] results = null;
            if (resultCode == RESULT_OK) {
                if (data != null) {
                    String dataString = data.getDataString();
                    ClipData clipData = data.getClipData();
                    if (clipData != null) {
                        results = new Uri[clipData.getItemCount()];
                        for (int i = 0; i < clipData.getItemCount(); i++) {
                            ClipData.Item item = clipData.getItemAt(i);
                            results[i] = item.getUri();
                        }
                    }
                    if (dataString != null) {
                        results = new Uri[]{Uri.parse(dataString)};
                    }
                }
            }
            mUploadCallbackAboveL.onReceiveValue(results);
            mUploadCallbackAboveL = null;
        }
    }

    @Override
    protected void onDestroy() {
        if (mBaseWebView != null) {
            mBaseWebView.onDestroy();
        }
        if (mWebView != null) {
            mWebView.removeAllViews();
            ((ViewGroup) mWebView.getParent()).removeView(mWebView);
            mWebView.clearHistory();
            mWebView.destroy();
        }
        if (getCleanCookie()) {
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.removeAllCookie();
        }
        super.onDestroy();
    }

    /**
     * 执行js函数
     */
    protected void evaluateJavascript(String script) {
        if (mWebView == null) {
            return;
        }
        mWebView.evaluateJavascript(script, value -> {

        });
    }

    public WebView getWebView() {
        return mWebView;
    }
}
